using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dtos.BasicView;
using ShopForWeb.Dtos.ViewModel;
using ShopForWeb.Models.Basic;
using ShopForWeb.Models.DbContexts;

namespace ShopForWeb.Services
{
  public class ShoppingCartServices
  {
    private ShopDbContext _Db;
    private IMapper _Mapper;
    public ShoppingCartServices(ShopDbContext db, IMapper mapper)
    {
      this._Db = db;
      this._Mapper = mapper;
    }

    public async Task<int> AddNewAsync(ShoppingCart shoppingCart)
    {
      var query = _Db.ShoppingCartSet
      .Where(s => s.UserId == shoppingCart.UserId && s.ProductId == shoppingCart.ProductId);
      int count = await query.CountAsync();
      if (count > 0)
        return 0;

      var entity = _Db.Entry<ShoppingCart>(shoppingCart);

      entity.State = EntityState.Added;
      return await _Db.SaveChangesAsync();
    }
    public async Task<int> DeleteAsync(int userId, int productId)
    {

      var entity = _Db.Entry<ShoppingCart>(new ShoppingCart()
      {
        UserId = userId,
        ProductId = productId
      });

      entity.State = EntityState.Deleted;
      return await _Db.SaveChangesAsync();
    }
    public async Task<int> CleanAsync(int userId)
    {
      var query = _Db.ShoppingCartSet.Where(s => s.UserId == userId);
      _Db.ShoppingCartSet.RemoveRange(query);
      return await _Db.SaveChangesAsync();
    }
    public async Task<PageView<ShoppingCartView>> GetPageAsync(int userId, int page, int size)
    {
      var query = _Db.ShoppingCartSet.Where(s => 1 == 1);
      query = query.Where(s => s.UserId == userId)
      .OrderBy(s => s.ProductId);
      PageView<ShoppingCartView> result = new PageView<ShoppingCartView>();
      result.Total = await query.CountAsync();

      var list = await query.Skip((page - 1) * size).Take(size).ToListAsync();//取出结果的一部分
      result.Data = _Mapper.Map<List<ShoppingCartView>>(list);

      return result;
    }
  }
}
